package com.pingguopifa.dao.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.pingguopifa.dao.UserDAO;
import com.pingguopifa.domain.User;

public class UserDAOHibernate extends HibernateDaoSupport implements UserDAO{
	
	private final static Logger LOGGER = Logger.getLogger(UserDAOHibernate.class);

	@Override
	public User getUserByUsername(String userName) {
		String hql = "from User as user inner join fetch user.roles  where user.username ='"+userName+"'";
		LOGGER.debug("userByUserName hql: " + hql);
		Session session = getSession();
		User user = null;
		@SuppressWarnings("rawtypes")
		List list = session.createQuery(hql).list();
		LOGGER.debug("userget List: " + list);
		LOGGER.debug("userget List size: " + list.size());
		if (list.size() > 0) {
			Object object = list.get(0);
			if (object != null) {
				user = (User) object;
			}
			releaseSession(session);
		}
		return user;
	}

	@Override
	public User loadUserByUsername(String userName) throws UsernameNotFoundException {
		@SuppressWarnings("unchecked")
		List<User> users = getHibernateTemplate().find("FROM User user inner join fetch user.roles WHERE user.username = ? ", userName);
		LOGGER.debug("userload List: " + users);
		LOGGER.debug("userload List size: " + users.size());
		if(users.isEmpty()) {
            throw new UsernameNotFoundException("User " + userName + " has no GrantedAuthority");
        }
        return users.get(0);
	}

}
